package org.jeecg.modules.business.controller;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.business.entity.BusOrderFee;
import org.jeecg.modules.business.enums.FeeType;
import org.jeecg.modules.business.service.IBusOrderFeeService;
import org.jeecg.modules.business.vo.RoomOrderFeeVo;
import org.jeecg.modules.rooms.entity.CesHouseLongRentCharge;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

 /**
 * @Description: bus_order_fee
 * @Author: jeecg-boot
 * @Date:   2023-04-08
 * @Version: V1.0
 */
@Api(tags="bus_order_fee")
@RestController
@RequestMapping("/business/busOrderFee")
@Slf4j
public class BusOrderFeeController extends JeecgController<BusOrderFee, IBusOrderFeeService> {
	@Autowired
	private IBusOrderFeeService busOrderFeeService;


	/**
	 * 分页列表查询
	 *
	 * @param busOrderFee
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "bus_order_fee-分页列表查询")
	@ApiOperation(value="bus_order_fee-分页列表查询", notes="bus_order_fee-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<BusOrderFee>> queryPageList(BusOrderFee busOrderFee,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<BusOrderFee> queryWrapper = QueryGenerator.initQueryWrapper(busOrderFee, req.getParameterMap());
		Page<BusOrderFee> page = new Page<BusOrderFee>(pageNo, pageSize);
		IPage<BusOrderFee> pageList = busOrderFeeService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	/**
	 *   添加
	 *
	 * @param busOrderFee
	 * @return
	 */
	@AutoLog(value = "bus_order_fee-添加")
	@ApiOperation(value="bus_order_fee-添加", notes="bus_order_fee-添加")
	//@RequiresPermissions("business:bus_order_fee:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody BusOrderFee busOrderFee) {
		busOrderFeeService.save(busOrderFee);
		return Result.OK("添加成功！");
	}

	 @AutoLog(value = "bus_order_fee-添加")
	 @ApiOperation(value="bus_order_fee-添加", notes="bus_order_fee-添加")
	 //@RequiresPermissions("business:bus_order_fee:add")
	 @PostMapping(value = "/saveBatch")
	 @Transactional(rollbackFor = Exception.class)
	 public Result<Boolean> add(@RequestBody List<BusOrderFee> busOrderFeeList, String hotelId) {
		 return Result.OK(busOrderFeeService.collectionBatch(busOrderFeeList, hotelId));
	 }

	 @AutoLog(value = "bus_order_fee-预约单添加押金")
	 @ApiOperation(value="bus_order_fee-预约单添加押金", notes="bus_order_fee-预约单添加押金")
	 //@RequiresPermissions("business:bus_order_fee:add")
	 @PostMapping(value = "/saveBookingDeposit")
	 @Transactional(rollbackFor = Exception.class)
	 public Result<Boolean> saveBookingDeposit(@RequestBody List<BusOrderFee> busOrderFeeList, String hotelId) {
		 String bookingOrderId = String.valueOf(IdWorker.getId());
		 busOrderFeeList.forEach(e -> {
			 e.setBookingOrderId(bookingOrderId);
		 });
		 Boolean success = busOrderFeeService.collectionBatch(busOrderFeeList, hotelId);
		 return success ? Result.OK(bookingOrderId) : Result.error("押金收取失败");
	 }

	 @AutoLog(value = "bus_order_fee-预约单添加押金")
	 @ApiOperation(value="bus_order_fee-预约单添加押金", notes="bus_order_fee-预约单添加押金")
	 //@RequiresPermissions("business:bus_order_fee:add")
	 @GetMapping(value = "/getBookingDeposit")
	 public Result<List<BusOrderFee>> getBookingDeposit(String bookingOrderId, String hotelId) {
		 List<BusOrderFee> busOrderFees = service.list(Wrappers.<BusOrderFee>lambdaQuery().eq(BusOrderFee::getBookingOrderId, bookingOrderId).eq(BusOrderFee::getBookingYj, true));
		 return Result.OK(busOrderFees);
	 }

	 @AutoLog(value = "bus_order_fee-退款")
	 @ApiOperation(value="bus_order_fee-退款", notes="bus_order_fee-退款")
	 //@RequiresPermissions("business:bus_order_fee:add")
	 @Transactional(rollbackFor = Exception.class)
	 @PostMapping(value = "/refundBatch")
	 public Result<Boolean> refundBatch(@RequestBody List<BusOrderFee> busOrderFeeList,String hotelId) {
		 List<String> feeIds = busOrderFeeList.stream().map(BusOrderFee::getId).collect(Collectors.toList());
		 if (feeIds.isEmpty()){
			 return Result.OK();
		 }
		 // 被退款的收费订单
		 List<BusOrderFee> originalFees = busOrderFeeService.listByIds(feeIds);
		 if (originalFees.size() != feeIds.size()){
			 throw new JeecgBootException("未找到收款单");
		 }
		 // 找出已结算的收款单对应的消费单id
		 List<String> consumeFeeIds = originalFees.stream().filter(e -> ObjectUtil.equals(e.getPreferentialStatus(), 2))
				 .map(BusOrderFee::getConsumeFeeId).collect(Collectors.toList());
		 List<BusOrderFee> allRelevanceFees = new ArrayList<>();
		 if (!consumeFeeIds.isEmpty()){
			 // 所有关联的收款单。（一个消费单可能对应多个收款单，退一个收款的，与之同一个消费单的收款单都要退掉）
			 allRelevanceFees = busOrderFeeService.list(Wrappers.<BusOrderFee>lambdaQuery().in(BusOrderFee::getConsumeFeeId, consumeFeeIds));
		 }

		 // 找出已结算的收款单id
		 List<String> collectionFeeIds = allRelevanceFees.stream().filter(e -> ObjectUtil.equals(e.getPreferentialStatus(), 2))
				 .map(BusOrderFee::getId).collect(Collectors.toList());
		 // 将结算的订单改为未结算
		 consumeFeeIds.addAll(collectionFeeIds);
		 LambdaUpdateWrapper<BusOrderFee> wrapper = new LambdaUpdateWrapper<>();
		 wrapper.set(BusOrderFee::getPreferentialStatus,1);
		 wrapper.in(CollUtil.isNotEmpty(consumeFeeIds),BusOrderFee::getId, consumeFeeIds);
		 busOrderFeeService.update(wrapper);
		 return Result.OK(busOrderFeeService.refundBatch(busOrderFeeList, hotelId));
	 }

	 /**
	 *  编辑
	 *
	 * @param busOrderFee
	 * @return
	 */
	@AutoLog(value = "bus_order_fee-编辑")
	@ApiOperation(value="bus_order_fee-编辑", notes="bus_order_fee-编辑")
	//@RequiresPermissions("business:bus_order_fee:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody BusOrderFee busOrderFee) {
		busOrderFeeService.updateById(busOrderFee);
		return Result.OK("编辑成功!");
	}

	 /**
	  *  编辑
	  *
	  * @param
	  * @return
	  */
	 @AutoLog(value = "bus_order_fee-冲账")
	 @ApiOperation(value="bus_order_fee-冲账", notes="bus_order_fee-冲账")
	 @RequestMapping(value = "/strike-balance", method = {RequestMethod.PUT,RequestMethod.POST})
	 public Result strikeBalance(@RequestBody List<BusOrderFee> busOrderFeeList) {
		 return Result.OK(busOrderFeeService.strikeBalance(busOrderFeeList));
	 }


	 /**
	  *  编辑
	  *
	  * @param
	  * @return
	  */
	 @AutoLog(value = "bus_order_fee-冲账单列表")
	 @ApiOperation(value="bus_order_fee-冲账单列表", notes="bus_order_fee-冲账单列表")
	 @GetMapping(value = "/strike-balance-page")
	 public Result strikeBalancePage(@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
									 @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
									 @RequestParam(name="roomName",required=false) String roomName,
									 @RequestParam(name="preferentialStatus",required=false) Integer preferentialStatus,
									 @RequestParam(name="bookingOrderId",required=false) String bookingOrderId,
									 @RequestParam(name="startTime" ,required=false) @JsonFormat(pattern = "yyyy-MM-dd")  @DateTimeFormat(pattern="yyyy-MM-dd") DateTime startTime,
									 @RequestParam(name="endTime" ,required=false) @JsonFormat(pattern = "yyyy-MM-dd")  @DateTimeFormat(pattern="yyyy-MM-dd") DateTime endTime) {
		 Page<RoomOrderFeeVo> page = new Page<>(pageNo, pageSize);
		 IPage<RoomOrderFeeVo> pageList = busOrderFeeService.strikeBalancePage(page,roomName, preferentialStatus,bookingOrderId, startTime, endTime);
		 return Result.OK(pageList);
	 }

	 /**
	  *  编辑
	  *
	  * @param
	  * @return
	  */
	 @AutoLog(value = "bus_order_fee-退款列表")
	 @ApiOperation(value="bus_order_fee-退款列表", notes="bus_order_fee-退款列表")
	 @PostMapping(value = "/refundList")
	 public Result<List<BusOrderFee>> refundList(@RequestBody List<String> livingOrderIds) {
		 LambdaQueryWrapper<BusOrderFee> qw = new LambdaQueryWrapper<>();
		 qw.eq(BusOrderFee::getFeeType, FeeType.COLLECTION.getKey());
//		 qw.eq(BusOrderFee::getPreferentialStatus, 1);
		 qw.in(CollUtil.isNotEmpty(livingOrderIds), BusOrderFee::getLivingOrderId, livingOrderIds);
		 List<BusOrderFee> orderFees = busOrderFeeService.list(qw);
		 return Result.OK(orderFees);
	 }

	 /**
	  *  编辑
	  *
	  * @param
	  * @return
	  */
	 @AutoLog(value = "")
	 @ApiOperation(value="添加读表费", notes="添加读表费")
	 @PostMapping(value = "/addMeterFee")
	 public Result addMeterFee(@RequestBody List<CesHouseLongRentCharge> longRentChargeList) {
		 Boolean isSuccess = service.addMeterFee(longRentChargeList);
		 return isSuccess ? Result.OK("读表成功") : Result.error("读表失败");
	 }

	 /**
	  *  编辑
	  *
	  * @param
	  * @return
	  */
	 @AutoLog(value = "bus_order_fee-冲账退款时根据消费单查收款单")
	 @ApiOperation(value="bus_order_fee-冲账退款时根据消费单查收款单", notes="bus_order_fee-冲账退款时根据消费单查收款单")
	 @PostMapping(value = "/refundsByFeeId")
	 public Result<List<BusOrderFee>> refundsByFeeId(@RequestBody List<String> feeIds) {
		 LambdaQueryWrapper<BusOrderFee> qw = new LambdaQueryWrapper<>();
		 qw.eq(BusOrderFee::getFeeType, FeeType.COLLECTION.getKey());
		 qw.eq(BusOrderFee::getPreferentialStatus, 1);
		 qw.in(CollUtil.isNotEmpty(feeIds), BusOrderFee::getConsumeFeeId, feeIds);
		 List<BusOrderFee> orderFees = busOrderFeeService.list(qw);
		 return Result.OK(orderFees);
	 }


	 /**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "bus_order_fee-通过id删除")
	@ApiOperation(value="bus_order_fee-通过id删除", notes="bus_order_fee-通过id删除")
	//@RequiresPermissions("business:bus_order_fee:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		busOrderFeeService.removeById(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "bus_order_fee-批量删除")
	@ApiOperation(value="bus_order_fee-批量删除", notes="bus_order_fee-批量删除")
	//@RequiresPermissions("business:bus_order_fee:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.busOrderFeeService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "bus_order_fee-通过id查询")
	@ApiOperation(value="bus_order_fee-通过id查询", notes="bus_order_fee-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<BusOrderFee> queryById(@RequestParam(name="id",required=true) String id) {
		BusOrderFee busOrderFee = busOrderFeeService.getById(id);
		if(busOrderFee==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(busOrderFee);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param busOrderFee
    */
    //@RequiresPermissions("business:bus_order_fee:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, BusOrderFee busOrderFee) {
        return super.exportXls(request, busOrderFee, BusOrderFee.class, "bus_order_fee");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    //@RequiresPermissions("business:bus_order_fee:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, BusOrderFee.class);
    }

}
